package com.mediacloud.app.newsmodule.fragment.recommend;


import android.content.Context;

import com.mediacloud.app.assembly.interfaces.LoadNetworkBack;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.component.ComponentItem;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleListData;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.Spider;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.component.ComponentListViewX;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsLowApi;
import com.mediacloud.app.newsmodule.utils.NotifyEvent;
import com.mediacloud.app.quanzi.model.BaseDataListBean;
import com.mediacloud.app.quanzi.model.DongTaiBean;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.user.model.UserInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 智能推荐相关新闻
 */

public class ComponentRelatedRecommendNewsView extends BaseComponentRelatedView {

    private ComponentListViewX container;
    private List<ArticleItem> listData;
    CatalogItem cat = new CatalogItem();

    public ComponentRelatedRecommendNewsView(Context context) {
        super(context);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    int typeX = 1;// 1/2 圈子话题/活动，默认是1

    int page = 5;

    @Override
    public void setData(ArticleItem articleItem,String article_id, ComponentItem component, int type) {
        super.setData(articleItem,article_id, component, type);
        this.componentItem = component;
        componentItem.setText_align(1);
        header.setComponent(componentItem);
        this.vid = vid;
        this.article_id = article_id;
        this.componentId = component.getId() + "";
        componentItem = component;
        this.type = type;

        try {
            typeX = componentItem.orginDataObject.optJSONObject("other_field")
                    .optInt("recommend_type", 1);
                    page = componentItem.orginDataObject.optInt("page");
        } catch ( Exception e) {
            e.printStackTrace();
        }
        if (typeX == 1) {
            getCircle();
        } else {
            getActivityList();
        }

    }

    private void getActivityList() {
        DataInvokeUtil.activeList(1, page,new LoadNetworkBack<ArticleListData>(){

            @Override
            public void Success(ArticleListData result) {
                if (result.state) {
                    List<ArticleItem> listArticles = result.articleList;
                    if (listArticles == null || listArticles.size() == 0) {
                        return;
                    }
                    mRootView.setVisibility(VISIBLE);
                    setVisibility(VISIBLE);
                    listData = listArticles;
                    container.setData(listArticles, cat,"");
                }
            }

            @Override
            public void Failure(Object obj) {

            }

            @Override
            public void otherData(String result) {

            }
        },new ArticleListData());
    }

    private void getCircle() {
        UserInfo userInfo = UserInfo.getUserInfo(getContext());
        JSONObject json = new JSONObject();

        try {
            if (userInfo.isLogin()) {
                json.put("userId", userInfo.getUserid());
            }
            json.put("cmsAppId", DataInvokeUtil.Cms_App_Id);
            json.put("orderField", "publishDate");
            json.put("orderDirection", "desc");
            json.put("pageNumber", 1);
            json.put("pageSize", page);
        } catch (Exception e) {
            e.printStackTrace();
        }

        RequestBody body =
                RequestBody.create(MediaType.parse("application/json; charset=UTF-8"), json.toString());
        //SpiderCmsApi.getSpiderCmsApi(getContext())
        SpiderCmsLowApi.getSpiderCmsLowApi(getContext())
                .getAllDongTaiList(body, getContext().getString(R.string.tenantid)).enqueue(new Callback<BaseDataListBean<DongTaiBean>>(){

            @Override
            public void onResponse(Call<BaseDataListBean<DongTaiBean>> call, Response<BaseDataListBean<DongTaiBean>> response) {
                BaseDataListBean<DongTaiBean> bean= response.body();
                listData = new ArrayList<>();
                if (bean != null && bean.isSuccess()) {
                    for (int i =0 ;i< bean.getData().getPageRecords().size();i++) {
                        DongTaiBean item = bean.getData().getPageRecords().get(i);
                        ArticleItem articleItem = new ArticleItem();
                        Spider spider = new Spider();
                        spider.setUserNickName(item.getAddUser());
                        articleItem.setLogo(item.getLogo()) ;
                        articleItem.setTitle( item.getContent());
//                        articleItem.Author = item.getAddUser();
                        articleItem.setSpider(spider);
                        articleItem.setPublishdate(item.getAddDate());
                        articleItem.setHitCount(item.getHitCount());
                        articleItem.setType(1);
                        articleItem.setPublishDate_format(item.getHitCount()+"");
                        listData.add(articleItem);
                    }
                    mRootView.setVisibility(VISIBLE);
                    setVisibility(VISIBLE);
                    container.setCircle(true);
                    container.setDongtaiList(bean.getData().getPageRecords());
                    container.setData(listData, cat,"");
                }
            }

            @Override
            public void onFailure(Call<BaseDataListBean<DongTaiBean>> call, Throwable t) {

            }
        });
    }

    @Override
    public int setLayoutRes() {
        return R.layout.component_related_recommendation_new;
    }

    @Override
    public void initOtherViews() {
        container = Utility.findViewById(mRootView, R.id.container);
        container.setDetailComponentList(true);
    }

    @Override
    public void onDataSuccess(ArticleListData data) {
        List<ArticleItem> listArticles = data.articleList;
        if (listArticles == null || listArticles.size() == 0) {
            return;
        }
        mRootView.setVisibility(VISIBLE);
        this.setVisibility(VISIBLE);

        this.listData = listArticles;
        container.setData(listArticles, cat,"");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNotifyEvent(NotifyEvent event) {
        if (listData != null) {
            container.setData(listData, cat,"");
        }
    }

    @Override
    public void onDataFault(Object data) {

    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}